package com.shopAndMall.AppBuilder;

import java.util.ArrayList;
import com.shopAndMallAppBuilder.customViews.BestListFooter;
import com.shopAndMallAppBuilder.customViews.BestListFooterNoResult;

import android.content.Context;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

public class BestList extends Fragment{
	ArrayList<String> seqList;
	ArrayList<String> nameList;
	ArrayList<String> img0List;
	ArrayList<String> subjectList;
	ArrayList<String> priceList;
	GridView bestListView;
	ArrayAdapter<String> apdapter;
	ProgressBar bestListProgressBar;
	BestListFooter footerView;
	BestListFooterNoResult footerNoResultView;
	MotionEvent ev = null;
    boolean addFlag;
    static int loadingLimit = 8;
    int listStartNum;
    boolean loadingFlag;
    Context context;
    DataModelBestItems getDataModel;
    BestItemsAdapter bestItemsAdapter;
    BestItemsGridAdapter bestAdapterGrid;
	int selectionRow;
    UtilDBCreate dbHelper;
	SQLiteDatabase database;
	Handler footerHandler;
	LinearLayout gridHeader;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
			// We have different layouts, and in one of them this
			// fragment's containing frame doesn't exist. The fragment
			// may still be created from its saved state, but there is
			// no reason to try to create its view hierarchy because it
			// won't be displayed. Note this is not needed -- we could
			// just run the code below, where we would create and return
			// the view hierarchy; it would just never be used.
			return null;
		}
		
		listStartNum = 0;
		
		addFlag= false;
		context = getActivity().getApplicationContext();
        View v = inflater.inflate(R.layout.best_list, container, false);
        
        initDB();
		
        gridHeader = (LinearLayout)v.findViewById(R.id.gridHeader);
        bestListView = (GridView)v.findViewById(R.id.bestGrid);
        bestListView.setNumColumns(2);
        
        footerView = new BestListFooter(getActivity());
        
        footerNoResultView = new BestListFooterNoResult(getActivity());
        //bestListProgressBar = (ProgressBar)v.findViewById(R.id.bestListProgressBar);
        //bestListProgressBar.setVisibility(View.VISIBLE);
		//bestListView.addFooterView(footerView);
        //bestListView.addView(footerView);
        
		Handler parserHandler = new Handler() {
			public void handleMessage(Message msg) {
				if(msg.what == 0){
					getDataModel  = (DataModelBestItems) msg.obj;
					
					/*
					nameList = getDataModel.nameList;
					img0List = getDataModel.img0List;
					subjectList = getDataModel.subjectList;
					*/
					
					/* 일반어덥터 
					apdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, nameList);
					bestListView.setAdapter(apdapter);
					*/
					
					initLists();
					reMakeList(loadingLimit, 0);
					
				    //ImageDownloader.Mode mode = ImageDownloader.Mode.CORRECT;
					//bestListView.addFooterView(footerView);
					
					//bestItemsAdapter = new BestItemsAdapter(context, R.layout.best_list_row, null, orientation);
					bestAdapterGrid = new BestItemsGridAdapter(context);
					setterToAdapter();
					//bestListProgressBar.setVisibility(View.INVISIBLE);	
				    //bestListView.setAdapter(bestItemsAdapter);
					bestListView.setAdapter(bestAdapterGrid);
				}
			}
			
	    }; //end handler
	    
	    footerHandler = new Handler() {
			public void handleMessage(Message msg) {
				if(msg.what == 0){
					//bestListView.addFooterView(footerView);
			        //bestListProgressBar.setVisibility(View.VISIBLE);
				}else{
					//bestListView.removeFooterView(footerView);
			        //bestListProgressBar.setVisibility(View.INVISIBLE);
				}
			}
	    };
		
		BestItemsParser getBestItems = new BestItemsParser( getActivity(), parserHandler);
		getBestItems.start();
		
		bestListView.setOnScrollListener(new OnScrollListener(){

			@Override
			public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				Log.e("onScroll last", Integer.toString(arg1)+" / "+ Integer.toString(arg2)+" / "+ Integer.toString(arg3));
				
				if(arg1 <= 1){
					gridHeader.setVisibility(View.VISIBLE);
				}else if(arg1  == 0 ){
					gridHeader.setVisibility(View.VISIBLE);
				}else{
					gridHeader.setVisibility(View.GONE);
				}
				
				if(arg3 > 0 && arg1 + arg2 == arg3){
					if(loadingFlag == false){ //중복요청 막기 
						//Log.e("listStartNum + loadingLimit", Integer.toString(listStartNum + loadingLimit));
						//Log.e("getDataModel.nameList.size()", Integer.toString(getDataModel.nameList.size()));
						
						if ( listStartNum + loadingLimit <= getDataModel.nameList.size() ) {
							//sendMsg(footerHandler, true);
							addList();
						}else{
							sendMsg(footerHandler, false);
						  	//if(bestListView.getFooterViewsCount()==0){
							//	bestListView.addFooterView(footerNoResultView);
							//}
						}
					}
				}
			}

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub
				//Log.e("onScrollStateChanged","in");
							
			}});
        
        /*
		bestListView.setOnTouchListener(new OnTouchListener() {

			// 터치콘트롤
			float downX;
			float upX;

			public boolean onTouch(View v, MotionEvent event) {
				// Handle touch events here...
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				case MotionEvent.ACTION_DOWN:
					Log.e("ACTION_DOWN",
							"X position : " + event.getX());
					downX = event.getX();
					break;
				case MotionEvent.ACTION_POINTER_DOWN:
					break;
				case MotionEvent.ACTION_UP:
					Log.e("ACTION_UP",
							"X position : " + event.getX());
					upX = event.getX();
					// downUpDist(downX, upX);
					break;
				case MotionEvent.ACTION_POINTER_UP:
					break;
				case MotionEvent.ACTION_MOVE:
					break;
				}

				// 여기 true 고치기
				return false; // indicate event was handled
			}

		});
    	*/
        
    	bestListView.setOnLongClickListener(new OnLongClickListener(){
			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				Log.e("Long Click","in");
				return false;
			}});
		return v;
	}

	void addList() {
    	loadingFlag = true;

		listStartNum += loadingLimit;
		Log.e("listStartNum", Integer.toString(listStartNum));
		
		Runnable run = new Runnable()
	    {
	      @Override
	      public void run()
	      {
  			reMakeList(loadingLimit, listStartNum);
    		setterToAdapter();
    		//bestItemsAdapter.notifyDataSetChanged();
    		bestAdapterGrid.notifyDataSetChanged();
	  		loadingFlag = false;
	  		try{
				//sendMsg(footerHandler, false);
	  		}catch(Exception e){}
	  	  }
	    };
	    
	    Handler handler = new Handler();
	    handler.postDelayed(run, 1000);
	    //handler.post(run);
	}
	
	void reMakeList(int loadingLimit, int startNum){
		UtilLibs reMakeList = new UtilLibs();
		seqList = reMakeList.reMakeList(getDataModel.seqList, seqList, loadingLimit, startNum);
		nameList = reMakeList.reMakeList(getDataModel.nameList, nameList, loadingLimit, startNum);
		img0List = reMakeList.reMakeList(getDataModel.img0List, img0List, loadingLimit, startNum);
		subjectList = reMakeList.reMakeList(getDataModel.subjectList, subjectList, loadingLimit, startNum);
		priceList = reMakeList.reMakeList(getDataModel.priceList, priceList, loadingLimit, startNum);
	}
	
	void setterToAdapter(){
		//데이터를 넘겨주는 세터임 - 가시적을 위해
		//bestItemsAdapter.setterData(img0List, nameList, subjectList, seqList, priceList);
		bestAdapterGrid.setterData(img0List, nameList, subjectList, seqList, priceList);
	}
	
	void initLists(){
		seqList = new ArrayList<String>();
        nameList = new ArrayList<String>();
        img0List = new ArrayList<String>();
        subjectList = new ArrayList<String>();
        priceList = new ArrayList<String>();
	}
	
	void initDB(){
		dbHelper =  new UtilDBCreate(getActivity());
		database = dbHelper.getWritableDatabase(); //초기 db, 테이블 생성 
	}
	
	void sendMsg(Handler mHandler, boolean flag) {
		if (flag == true ) {
			Message msg = Message.obtain();
			msg.what = 0;
			mHandler.sendMessage(msg);
		} else {
			Message msg = Message.obtain();
			msg.what = 1;
			mHandler.sendMessage(msg);
		}
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Context context = getActivity().getApplicationContext();
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);

	    switch(newConfig.orientation) {
	        case Configuration.ORIENTATION_PORTRAIT:
	        	bestListView.setNumColumns(2);
	        	bestAdapterGrid.notifyDataSetChanged();
	            break;
	        case Configuration.ORIENTATION_LANDSCAPE:  
	        	bestListView.setNumColumns(3);
	        	bestAdapterGrid.notifyDataSetChanged();

	        	break;
	    }
	}
	
	
}
